<template>
  <modal-bg ref="modalRef">
    <view style="position: absolute; top: 10%; left: 50rpx; width: 650rpx">
      <image
        @click="hide"
        src="https://static.tospurfang.com/asset/close.png"
        mode="scaleToFill"
        style="width: 36rpx; height: 36rpx; position: absolute; right: 0; top: -50rpx" />
      <image
        @click="onPreview"
        :src="info.image"
        mode="aspectFit"
        style="width: 650rpx; height: 70vh; border-radius: 16rpx" />
      <view
        @click="onSave"
        style="
          width: 650rpx;
          height: 100rpx;
          background: #042275;
          border-radius: 16rpx;
          font-size: 32rpx;
          color: #ffffff;
          line-height: 100rpx;
          margin-top: 20rpx;
          text-align: center;
        ">
        下载至相册
      </view>
    </view>
  </modal-bg>
</template>

<script setup>
  import modalBg from './modal-bg.vue'

  import { ref } from 'vue'
  const emits = defineEmits(['download'])

  const info = ref({})
  const modalRef = ref(false)
  const show = (inf) => {
    info.value = inf
    modalRef.value.show()
  }
  const hide = () => {
    modalRef.value.hide()
  }

  function onSave() {
    emits('download')
    if (info.value.local) {
      uni.saveImageToPhotosAlbum({
        filePath: info.value.image,
        success(res) {
          if (res.errMsg.indexOf(':ok') > 0) {
            uni.showToast({
              icon: 'none',
              title: '保存成功'
            })
          }
        }
      })
    } else {
      uni.downloadFile({
        url: info.value.image,
        success: (res) => {
          if (res.statusCode === 200) {
            uni.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success(res) {
                if (res.errMsg.indexOf(':ok') > 0) {
                  uni.showToast({
                    icon: 'none',
                    title: '保存成功'
                  })
                }
              }
            })
          }
        }
      })
    }
  }

  function onPreview() {
    uni.previewImage({ urls: [info.value.image] })
  }

  defineExpose({ show, hide })
</script>

<style lang="scss" scoped></style>
